package com.xp.record25.bio.nio.worker;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class BossWorkerServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel bossChannel = ServerSocketChannel.open();
        bossChannel.configureBlocking(false);
        bossChannel.bind(new InetSocketAddress(8888));
        Selector selector = Selector.open();
        bossChannel.register(selector, SelectionKey.OP_ACCEPT);
        AtomicInteger atomicInteger = new AtomicInteger();
        Worker[] workers = new Worker[2];

        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                SocketChannel sc = bossChannel.accept();
                sc.configureBlocking(false);
                //取模就是 负载均衡算法
                int i = atomicInteger.getAndIncrement() % workers.length;
                Worker worker = workers[i];
                if (Objects.isNull(worker)) {
                    worker = new Worker("worker-" + i);
                    workers[i]  = worker;
                }
                worker.registry(sc);
                System.out.println("sc = " + sc);
            }
        }


    }

    static class Worker implements Runnable {

        private String name;
        private Thread thread;
        private Selector selector;
        private volatile Boolean flag = Boolean.FALSE;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue();

        public Worker() {
        }

        public Worker(String name) {
            this.name = name;
        }

        public void registry(SocketChannel channel) throws IOException {
            if (!flag) {
                this.thread = new Thread(this, this.name);
                this.selector = Selector.open();
                thread.start();
                this.flag = Boolean.TRUE;
            }

            //添加好了运行的方法之后在发放通行证，
            //这里为什么要这么写呢？是因为如果
            // selector.select(); 阻塞了线程 channel.register(selector, SelectionKey.OP_READ); 就注册不了可读事件了
            queue.add(() -> {
                try {
                    channel.register(selector, SelectionKey.OP_READ);
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                }
            });
            //发放通行证，唤醒 selector
            selector.wakeup();
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Runnable poll = queue.poll();
                    if (Objects.nonNull(poll)) {
                        poll.run();
                    }
                    selector.select();
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        SocketChannel channel = (SocketChannel) key.channel();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            channel.read(buffer);
                            buffer.flip();
                            System.out.println(Thread.currentThread().getName() + " 接收到消息为 = " + StandardCharsets.UTF_8.decode(buffer));
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
